// home/04order/detail.js
var co = require('../../js/common.js')
var ws = require('../../js/websocket.js')
var app = getApp()
var _this, _data, room_id, pageNo = {}, dialogs = {}, content = ''
var client_id = '', inRoomUser, selected_uid = ''
Page({
   data: {
      order: {},
      creator: {},
      content: '',
      dialogs: [],
      self_uid: '',
      scrollView2_h: 0,
      win_w: 0,
      to_view: '',
      floatViewShow: 0,
      p: { x: 50, y: 200 },
      striveMasterList: []
   },

   onLoad: function (opt) {
      _this = this
      _data = this.data
      //创建房间
      room_id = 'kx' + opt.order_id
      wx.setNavigationBarTitle({ title: room_id + '号订单房间' })

      var sys = wx.getSystemInfoSync()
      co.getSelfApi('order/mg/getOrderDetail', opt, function (res) {
         _this.setData({
            order: res.data,
            self_uid: app.aData.userInfo.unionid,
            scrollView2_h: sys.windowHeight - 40 - 100 - 70,
            win_w: sys.windowWidth - 8 * 2
         })
         //检查获取本地对话缓存
         _this.getLocalDialogList()
         //获取订单创建者信息
         _this.getCreatorInfo(res.data.creator_uid)
      })
   },
   //获取创建者信息
   getCreatorInfo: function (creator_uid) {
      var param = { unionid: creator_uid }
      co.getShareApi('user/mg/getuserinfo2', param, function (res) {
         _this.setData({ creator: res.data })
         _this.saveLogs(res.data)
         //获取争取师傅列表
         _this.getStriveMasterList()
      })
   },
   //获取争取师傅列表
   getStriveMasterList: function () {
      var param = { order_id: _data.order.order_id }
      co.getSelfApi('order/Get/striveMasterList', param, function (res) {
         for (var i = 0; i < res.data.length; i++) {
            res.data[i].imgMode = 'gray'
         }
         var list = [{
            unionid: _data.creator.unionid,
            avatarUrl: _data.creator.avatarUrl,
            imgMode: ''
         }]
         // console.log('【【【res.data】】】', res.data)
         _this.setData({ striveMasterList: list.concat(res.data) })
         _this.create_room()
      })
   },
   //检查获取本地对话
   getLocalDialogList: function () {
      if (co.empty(pageNo[room_id])) {
         pageNo[room_id] = 1
      }
      if (co.empty(dialogs[room_id])) {
         _this.getDialogList()
      } else {
         _this.setData({ dialogs: dialogs[room_id] })
      }
   },
   //获取对话列表
   getDialogList: function () {
      var td = this.data
      var param = {
         order_id: td.order.order_id,
         owner_uid: td.order.creator_uid,
         self_uid: td.self_uid,
         pageNo: pageNo[room_id]
      }
      co.getSelfApi('dialog/c/getlist', param, function (res) {
         if (res.code == 0) {
            var list = res.data.concat(_this.data.dialogs)
            _this.setData({ dialogs: list })
            if (pageNo[room_id] == 1) {
               //滚动最底页
               _this.setData({ to_view: 'toView' })
            }
            pageNo[room_id]++
         } else if (pageNo[room_id] > 1) {
            co.toast('没有了！别拉了！')
         }
      })
   },
   //弹出目录
   select: function (e) {
      selected_uid = e.target.id
      if (this.data.self_uid != this.data.creator.unionid) {
         // wx.showToast({ title: '非业主点击' })
         return
      }
      this.setData({
         p: { x: e.detail.x + 10, y: e.detail.y - 60 },
         floatViewShow: this.data.floatViewShow ? 0 : 1
      })
   },
   //选定他上门检查
   selectedToDoor: function () {
      var param = {
         order_id: _data.order.order_id,
         unionid: selected_uid,
         get_status: 2
      }
      co.getSelfApi('order/Get/getStatusSet', param, function (res) {
         co.modal('您选中了“' + _this.getMasterName() + '”，等待他上门勘查')
         _data.order.status = param.get_status
         _this.setData({
            floatViewShow: 0,
            order: _data.order
         })
      })
   },
   //获取师傅昵称
   getMasterName: function () {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         if (selected_uid == list[i].unionid) {
            return list[i].real_name
         }
      }
   },
   //获取师傅是否被选
   getMasterState: function () {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         if (selected_uid == list[i].unionid) {
            return list[i].get_status
         }
      }
   },
   //对他说
   sayToHim: function (e) {
      if (e.target.id != '') {
         selected_uid = e.target.id
      }
      this.setData({ content: '@' + _this.getMasterName() + ' ' + _data.content })
      if (_data.floatViewShow) {
         this.setData({ floatViewShow: 0 })
      }
   },
   //跳转到此师傅页面
   toHisInfo: function () {
      wx.navigateTo({ url: '/pc/02user/masterInfo?unionid=' + selected_uid + '&get_status=' + this.getMasterState() })
      this.setData({ floatViewShow: 0 })
   },
   //创建房间
   create_room: function () {
      var info = app.aData.userInfo
      info.type = 'login'
      this.onSocketMsg()
      ws.loginWebsocket(info, room_id, function (res) {
         console.log('【已创建房间】' + room_id, res)
      })
   },
   //监听websocket
   onSocketMsg: function () {
      ws.setDetailJsOnSocket(function (res) {
         console.log('【detail.js收到监听socket回调】', res)
         if (res.type == 'login') {
            if (res.client_list) {
               client_id = res.client_id
               inRoomUser = res.client_list
               _this.setAvatarImgMode()
            } else if (res.room_id == room_id) {
               _this.loginUser(res.client_id, res)
            }
         }

         if (res.type == 'logout') {
            if (room_id == res.from_room_id) {
               _this.logoutUser(res.from_client_id)
               //如果自已退出，则重建房间
               if (client_id == res.from_client_id) {
                  _this.create_room(room_id);
               }
            }
         }

         if (res.type == 'say' && res.room_id == room_id) {
            if (app.aData.userInfo.unionid == _data.order.creator_uid) {
               _this.addDialog(res.content)
            } else if (_data.order.creator_uid == res.content.from_unionid || res.content.from_unionid == app.aData.userInfo.unionid) {
               _this.addDialog(res.content)
            }
         }
      })
   },
   //增加聊天记录
   addDialog: function (content) {
      var list = _this.data.dialogs
      list.push(content)
      //滚动最底页
      _this.setData({ dialogs: list })
      _this.setData({ to_view: 'toView' })
   },
   //更新在线离线用户头像
   setAvatarImgMode: function (onLineUserList) {
      var list = _data.striveMasterList
      for (var i = 0; i < list.length; i++) {
         list[i].imgMode = 'gray'
         for (var key in inRoomUser) {
            if (list[i].unionid == inRoomUser[key].unionid) {
               list[i].imgMode = ''
            }
         }
      }
      _this.setData({ striveMasterList: list })
   },
   //登入用户加上
   loginUser: function (client_id, res) {
      inRoomUser[res.client_id] = { unionid: res.unionid }
      _this.setAvatarImgMode()
   },
   //退出用户减掉
   logoutUser: function (client_id) {
      delete inRoomUser[client_id]
      _this.setAvatarImgMode()
   },
   //获取待发话内容
   getContent: function (e) {
      this.data.content = e.detail.value
      content = e.detail.value
   },
   //保存发话内容websocket并保存
   sendAndSave: function (e) {
      var param = {
         order_id: this.data.order.order_id,
         from_unionid: app.aData.userInfo.unionid,
         from_avatarUrl: app.aData.userInfo.avatarUrl,
         from_nickName: app.aData.userInfo.nickName,
         to_unionid: 'all',
         content: e.detail.value.content
      }
      co.getSelfApi('dialog/c/sayToSave', param, function (res) {
         _this.setData({ content: '' })
         content = ''//本页全局变量也置空
         ws.sendToAll(res.data, function (cb) {
            console.log('【sendToAll发送成功】', cb)
         })
      })
   },
   //退出时
   onUnload: function () {
      inRoomUser = {}

      dialogs[room_id] = this.data.dialogs
      ws.setDataOrderRoomId(null)

      var info = app.aData.userInfo
      info.type = 'logout'
      info.client_id = client_id
      ws.loginWebsocket(info, room_id)
      client_id = ''
   },

   onShareAppMessage: function () { },

   saveLogs: function (userInfo) {
      var keys = ['avatarUrl', 'unionid', 'openid', 'nickName']
      var log = co.addValueForKey({}, userInfo, keys)
      log.client = 'order:dialog:' + room_id
      co.getSelfApi('user/Umg/saveLogs', log, function (res) {
         console.log('【日志保存结果】', res)
      })
   }
})

